#include "utility.hpp"
#include "utils/io_utils.hpp"
#include "utils/str_utils.hpp"

#include <filesystem>

std::map<std::string, std::string> AnalysisScriptFileContent(const std::string &path)
{
    std::map<std::string, std::string> result;

    const auto content = ReadTextFile(path);
    if (!content.empty()) {
        // find token headers
        std::string token_key, token_value;
        std::string::size_type pos = 0, last = 0;
        while((pos = content.find('@', last)) != std::string::npos) {
            // @xxx
            auto space = content.find(' ', pos);
            auto line_end = content.find('\n', pos);
            token_key = trim_copy(content.substr(pos+1, std::min<decltype(pos)>(space, line_end)-pos-1));
            if (token_key.ends_with("_begin")) {
                // 在 _begin 和 _end 之间
                auto end = content.find('@' + token_key.substr(0, token_key.length()-6) + "_end", pos);
                if (end == std::string::npos) {
                    result.clear();
                    break;
                }
                auto prefix_length = token_key.length() + 2;
                token_value = trim_copy(content.substr(pos + prefix_length, end - pos - prefix_length));
                pos = end;
                token_key = token_key.substr(0, token_key.length() - 6);
            } else {
                // 在此行后面
                auto end = content.find('\n', space);
                token_value = content.substr(space+1, end-space);
                token_value = trim_copy(token_value);
                pos = end;
            }
            result.emplace(std::move(token_key), trim_copy(token_value));
            last = pos + 1;
        }
    }
    return result;
}

std::string GetFileName (const std::string &path)
{
    return std::filesystem::path {path}.stem ().string ();
}

double GetFileTime (const std::string &path)
{
    return (double)std::filesystem::last_write_time (path).time_since_epoch ().count ();
}
